package com.wenkang.stu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wenkang.stu.enums.ExceptionEnums;
import com.wenkang.stu.exception.KangException;
import com.wenkang.stu.pojo.SysRole;
import com.wenkang.stu.pojo.SysUserRole;
import com.wenkang.stu.service.SysRoleService;
import com.wenkang.stu.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("role")
@RestController
public class RoleController {

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserRoleService userRoleService;

    @GetMapping
    public ResponseEntity<List> selectRoles() {
        List<SysRole> roles = roleService.list();
        return ResponseEntity.ok(roles);
    }

    /**
     * 根据用户Id查询所有角色
     *
     * @param userId
     * @return
     */
    @GetMapping("user/{userId}")
    public ResponseEntity<List> selectRoleIds(@PathVariable("userId") Integer userId) {
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        List<SysUserRole> userRoles = userRoleService.list(queryWrapper.eq("user_id", userId));
        List<Integer> roleIds = userRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        return ResponseEntity.ok(roleIds);
    }

    @PutMapping("menu")
    public ResponseEntity<Void> updateRoleMenu(@RequestBody SysRole role) {
        userRoleService.updateRoleMenu(role);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @PostMapping
    public ResponseEntity<Void> insertRole(@RequestBody SysRole sysRole) {
        if (!roleService.save(sysRole)) {
            throw new KangException(ExceptionEnums.CREATED_ERROR);
        }
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @PutMapping
    public ResponseEntity<Void> updateRole(@RequestBody SysRole sysRole) {
        if (!roleService.updateById(sysRole)) {
            throw new KangException(ExceptionEnums.UPDATE_ERROR);
        }
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @DeleteMapping("{roleId}")
    public ResponseEntity<Void> deleteRole(@PathVariable("roleId") Integer roleId) {
        if (!roleService.removeById(roleId)) {
            throw new KangException(ExceptionEnums.DELETE_ERROR);
        }
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
}
